#include "NetGame.h"
#include <QDebug>
NetGame::NetGame(bool server)
{
    _server = NULL;//初始化为null
    _socket = NULL;

    if(server)
    {
        _server = new QTcpServer(this);     //创建服务器
        _server->listen(QHostAddress::Any, 9999);//监听端口9999

        connect(_server, SIGNAL(newConnection()),
                this, SLOT(slotNewConnection()));//槽函数连接
    }
    else    //是客户端
    {
        _socket = new QTcpSocket(this);
        _socket->connectToHost(QHostAddress("127.0.0.1"), 9999);

        connect(_socket, SIGNAL(readyRead()),
                this, SLOT(slotRecv()));
    }
}

NetGame::~NetGame()
{

}

void NetGame::click(int id, int row, int col)
{
    if(_selectid == -1 && id != -1)
    {
        if(_s[id]._red != _bSide)   //只能点自己的棋。即一边只能点红棋，一边只能点黑棋
            return;
    }

    Board::click(id, row, col);//一定要调用父类的click，父类的，即下棋

    /* 把下棋信息发送给对方 */
    char buf[4];
    buf[0] = 2;
    buf[1] = 9-row;
    buf[2] = 8-col;
    buf[3] = id;
    _socket->write(buf, 4);
}

void NetGame::slotRecv()
{
    QByteArray ba = _socket->readAll();//返回字节数组
    char cmd = ba[0];
    if(cmd == 1)
    {
        // 初始化
        char data = ba[1];
        init(data==1);  //data==1为true则红棋在下，先走
    }
    else if(cmd==2)
    {
        int row = ba[1];
        int col = ba[2];
        int id = ba[3];
        Board::click(id, row, col);//一定是调用父类的 来移动
    }
}

void NetGame::slotNewConnection()
{
    if(_socket)//防止两个及以上的连接，即只能一对一
        return;

    _socket = _server->nextPendingConnection();//nextPendingConnection返回QTcpsocket
    //qDebug() << "connect";
    connect(_socket, SIGNAL(readyRead()),   //客户端给服务器发数据，服务器也能收到
            this, SLOT(slotRecv()));

    /* 给对方发送数据  两个字节，*/
    char buf[2];
    buf[0] = 1;
    buf[1] = 0; //服务器执红

    _socket->write(buf, 2);//通过socket发送给对方

    init(buf[1]==0);     //buf[1]==0为true则黑棋在下，其实是和slotRecv()中旋转180度了
}

